/**
 * @param {number[]} nums
 * @return {number[]}
 */
var nextGreaterElements = function (nums) {
  const ans = []
  let len = nums.length
  for (let i = 0; i < nums.length; i++) {
    let flag1 = false
    let flag2 = false
    for (let j = i + 1; j % len < nums.length; j++) {
      if (nums[j] > nums[i]) {
        ans.push(nums[j])
        flag1 = true
        break
      }
    }
    if (!flag1) {
      for (let j = 0; j < i; j++) {
        if (nums[j] > nums[i]) {
          ans.push(nums[j])
          flag2 = true
          break
        }
      }
    }
    if (!flag1 && !flag2) ans.push(-1)
  }
  return ans
}
// 栈怎么做？
var nextGreaterElements2 = function (nums) {
  const stack = []
  let len = nums.length
  let ans = new Array(len).fill(-1)
  for (let i = 0; i < 2 * len; i++) {
    while (stack.length !== 0 && nums[stack[stack.length - 1] % len] < nums[i % len]) {
      let index = stack.pop()
      ans[index % len] = nums[i % len]
    }
    stack.push(i)
  }
  return ans
}
console.log(nextGreaterElements2([1, 2, 1]))